package thread;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author liweimin
 * @date 2021/2/21 17:02
 * @description 多线程安全例题：银行有一个账户，有两个储户分别向同一个帐户存3000元，每次100.存3次，存完打印账户余额
 * @since
 */
public class AccountTest {
    public static void main(String[] args) {
        Account account = new Account();
        new Thread(account).start();
        new Thread(account).start();
        new Thread(account).start();
    }
}

class Account implements Runnable {
    //账户余额
    private int balance = 0;

    //    @Override
//    public synchronized void run() {
//        for (int i = 0; i < 3; i++) {
//            balance += 1000;
//            try {
//                Thread.sleep(100);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//            System.out.println(Thread.currentThread().getName() + "存钱成功，余额为：" + balance);
//        }
//    }
    ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {

        for (int i = 0; i < 3; i++) {
            lock.lock();
            balance += 1000;
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "存钱成功，余额为：" + balance);
            lock.unlock();
        }

    }
}
